
const fs = require('fs')
const https = require('https')
const http = require('http')
const url = require('url')

const options = {
    key: fs.readFileSync('./indexls.com_nginx/indexls.com.key'),
    cert: fs.readFileSync('./indexls.com_nginx/indexls.com_bundle.crt'),
}
const https_server = https.createServer(options, (req, res) => {
    const method = req.method.toUpperCase()
    const path = url.parse(req.url, true).pathname
    if (method == 'OPTIONS') response(res, 'text/plain;charset=utf8;', 200, '批准OPTIONS请求', {})
    else if (method == 'GET') {
        // 获取用户IP4地址
        if (path == '/api/ip') response(res, 'text/plain;charset=utf8;', 200, '请求成功', req.connection.remoteAddress.replace('::ffff:', ''))
        else {
            response(res, 'text/plain;charset=utf8;', 403, '不存在api', {})
        }
    }
    else {
        response(res, 'text/plain;charset=utf8;', 403, '不支持请求方法', {})
    }
})

const http_server = http.createServer((req, res) => {
    const method = req.method.toUpperCase()
    const path = url.parse(req.url, true).pathname
    if (method == 'OPTIONS') response(res, 'text/plain;charset=utf8;', 200, '批准OPTIONS请求', {})
    else if (method == 'GET') {
        // 获取用户IP4地址
        if (path == '/api/ip') response(res, 'text/plain;charset=utf8;', 200, '请求成功', req.connection.remoteAddress.replace('::ffff:', ''))
        else {
            response(res, 'text/plain;charset=utf8;', 403, '不存在api', {})
        }
    }
    else {
        response(res, 'text/plain;charset=utf8;', 403, '不支持请求方法', {})
    }
})

https_server.listen(443, () => {
    console.log('https服务启动成功')
})

http_server.listen(80, () => {
    console.log('http服务启动成功')
})


//设置数据格式和编码以及结束响应
function response(res, dataType, status, msg, data) {
    let obj = {}
    obj.code = status //状态码代码
    obj.msg = msg //提示信息
    obj.data = data //返回数据
    res.writeHead(200, {
        "Content-Type": dataType, //数据类型
        "Access-Control-Allow-Origin": "*", //解决跨域关键
        "transfer-encoding": "chunked",
        "Access-Control-Allow-Headers": "*"
    })
    console.log('响应数据', JSON.stringify(obj))
    res.end(JSON.stringify(obj)) //结束响应
}